package com.lqk.demo.pessimisticlock.syncmode.sequencecontrol.alternately;

import lombok.extern.slf4j.Slf4j;

/**
 * 交替输出：WaitNotify
 * @author lqk
 * @date 2021/12/23 16:33
 *
 * 线程1：输出 a 5次
 * 线程2：输出 b 5次
 * 线程3：输出 c 5次
 *
 * 要求输出 abcabcabcabcabc 交替输出
 */
@Slf4j
public class TestWaitNotify {
    public static void main(String[] args) {
        WaitNotify wn = new WaitNotify(1,5);
        new Thread(()->{wn.print("a",1,2);},"t1").start();
        new Thread(()->{wn.print("b",2,3);},"t2").start();
        new Thread(()->{wn.print("c",3,1);},"t3").start();
    }
}

@Slf4j
class WaitNotify{
    // 等代标记
    private int flag;

    private int loopNumber;

    public WaitNotify(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }

    // 打印方法
    public void print(String str, int waitFlag, int nextFlag){
        for (int i = 0; i < loopNumber; i++) {
            synchronized (this){
                while (this.flag != waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug(str);
                this.flag = nextFlag;
                this.notifyAll();
            }
        }
    }
}
